package cn.woblog.recyclerviewsample;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class BasicUseActivity extends AppCompatActivity {

  private List<String> data = new ArrayList<>();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_basic_use);

    for (int i = 0; i < 50; i++) {
      data.add("Item " + i);
    }

    RecyclerView rv = (RecyclerView) findViewById(R.id.rv);

//如果你知道你的RecyclerView的高度在使用期间不会变化
// 使用此设置可以提高性能，后面会相应的文章分析为什么
    rv.setHasFixedSize(true);

//设置一个布局管理器
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    rv.setLayoutManager(linearLayoutManager);

//设置适配器
MyAdapter myAdapter = new MyAdapter(this);
rv.setAdapter(myAdapter);

  }

  class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private final LayoutInflater layoutInflater;

    public MyAdapter(Context context) {
      layoutInflater = LayoutInflater.from(context);
    }

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  return new MyViewHolder(
      layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false));
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
  String d = BasicUseActivity.this.data.get(position);
  holder.bindData(d);
}

@Override
public int getItemCount() {
  return data.size();
}

    class MyViewHolder extends RecyclerView.ViewHolder {

      private final TextView tv;

      public MyViewHolder(View itemView) {
        super(itemView);
        tv = (TextView) itemView.findViewById(android.R.id.text1);
      }

      public void bindData(String d) {
        tv.setText(d);
      }
    }
  }
}
